package com.gzc.just.play.last.war.sceneserver.battle.controller;

import com.gzc.just.play.last.war.sceneserver.battle.model.BattleInfo;
import com.gzc.just.play.last.war.sceneserver.battle.model.BattleUserInfo;
import com.gzc.just.play.last.war.sceneserver.battle.service.BattleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 战斗控制器
 * 提供HTTP接口处理战斗相关请求
 */
@RestController
@RequestMapping("/api/battle")
public class BattleController {
    
    private static final Logger log = LoggerFactory.getLogger(BattleController.class);
    
    @Autowired
    private BattleService battleService;
    
    /**
     * 创建新战斗
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createBattle(
            @RequestParam BattleInfo.BattleType battleType,
            @RequestParam Integer mapId,
            @RequestParam(defaultValue = "2") Integer maxPlayers) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            BattleInfo battle = battleService.createBattle(
                    battleType, mapId, maxPlayers, null, null);
            
            response.put("success", true);
            response.put("message", "战斗创建成功");
            response.put("battleId", battle.getBattleId());
            response.put("battle", battle);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建战斗失败", e);
            response.put("success", false);
            response.put("message", "创建战斗失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 玩家加入战斗
     */
    @PostMapping("/{battleId}/join")
    public ResponseEntity<Map<String, Object>> joinBattle(
            @PathVariable Long battleId,
            @RequestParam Long userId,
            @RequestParam String nickname,
            @RequestParam Long characterId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean result = battleService.joinBattle(battleId, userId, nickname, characterId);
            
            if (result) {
                response.put("success", true);
                response.put("message", "加入战斗成功");
                
                BattleInfo battle = battleService.getBattleInfo(battleId);
                response.put("battle", battle);
            } else {
                response.put("success", false);
                response.put("message", "加入战斗失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("加入战斗失败", e);
            response.put("success", false);
            response.put("message", "加入战斗失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 玩家离开战斗
     */
    @PostMapping("/{battleId}/leave")
    public ResponseEntity<Map<String, Object>> leaveBattle(
            @PathVariable Long battleId,
            @RequestParam Long userId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            battleService.leaveBattle(userId);
            
            response.put("success", true);
            response.put("message", "已离开战斗");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("离开战斗失败", e);
            response.put("success", false);
            response.put("message", "离开战斗失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 开始战斗
     */
    @PostMapping("/{battleId}/start")
    public ResponseEntity<Map<String, Object>> startBattle(@PathVariable Long battleId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean result = battleService.startBattle(battleId);
            
            if (result) {
                response.put("success", true);
                response.put("message", "战斗已开始");
                
                BattleInfo battle = battleService.getBattleInfo(battleId);
                response.put("battle", battle);
            } else {
                response.put("success", false);
                response.put("message", "无法开始战斗");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("开始战斗失败", e);
            response.put("success", false);
            response.put("message", "开始战斗失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 结束战斗
     */
    @PostMapping("/{battleId}/end")
    public ResponseEntity<Map<String, Object>> endBattle(
            @PathVariable Long battleId,
            @RequestParam Integer winnerTeamId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            battleService.endBattle(battleId);
            
            response.put("success", true);
            response.put("message", "战斗已结束");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("结束战斗失败", e);
            response.put("success", false);
            response.put("message", "结束战斗失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取战斗信息
     */
    @GetMapping("/{battleId}")
    public ResponseEntity<Map<String, Object>> getBattleInfo(@PathVariable Long battleId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            BattleInfo battle = battleService.getBattleInfo(battleId);
            
            if (battle != null) {
                response.put("success", true);
                response.put("battle", battle);
            } else {
                response.put("success", false);
                response.put("message", "战斗不存在");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取战斗信息失败", e);
            response.put("success", false);
            response.put("message", "获取战斗信息失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取用户所在战斗
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserBattle(@PathVariable Long userId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            BattleInfo battle = battleService.getUserBattle(userId);
            
            if (battle != null) {
                response.put("success", true);
                response.put("battle", battle);
            } else {
                response.put("success", false);
                response.put("message", "用户不在任何战斗中");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户战斗失败", e);
            response.put("success", false);
            response.put("message", "获取用户战斗失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取玩家战斗统计
     */
    @GetMapping("/player/{userId}/stats")
    public ResponseEntity<Map<String, Object>> getPlayerStats(@PathVariable Long userId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            BattleUserInfo stats = battleService.getPlayerBattleStats(userId);
            
            if (stats != null) {
                response.put("success", true);
                response.put("stats", stats);
            } else {
                response.put("success", false);
                response.put("message", "玩家不在战斗中");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取玩家统计失败", e);
            response.put("success", false);
            response.put("message", "获取玩家统计失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取活跃战斗列表
     */
    @GetMapping("/active")
    public ResponseEntity<Map<String, Object>> getActiveBattles() {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<BattleInfo> battles = battleService.getActiveBattles();
            
            response.put("success", true);
            response.put("battles", battles);
            response.put("count", battles.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取活跃战斗失败", e);
            response.put("success", false);
            response.put("message", "获取活跃战斗失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取活跃战斗数量
     */
    @GetMapping("/active/count")
    public ResponseEntity<Map<String, Object>> getActiveBattleCount() {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            int count = battleService.getActiveBattleCount();
            
            response.put("success", true);
            response.put("activeBattleCount", count);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取活跃战斗数量失败", e);
            response.put("success", false);
            response.put("message", "获取活跃战斗数量失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 记录玩家杀敌
     */
    @PostMapping("/player/{userId}/kill/{targetId}")
    public ResponseEntity<Map<String, Object>> recordKill(
            @PathVariable Long userId,
            @PathVariable Long targetId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            battleService.recordPlayerKill(userId, targetId);
            
            response.put("success", true);
            response.put("message", "已记录杀敌");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("记录杀敌失败", e);
            response.put("success", false);
            response.put("message", "记录杀敌失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 玩家受伤
     */
    @PostMapping("/player/{userId}/damage")
    public ResponseEntity<Map<String, Object>> playerTakeDamage(
            @PathVariable Long userId,
            @RequestParam Integer damage) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            battleService.playerTakeDamage(userId, damage);
            
            BattleUserInfo stats = battleService.getPlayerBattleStats(userId);
            
            response.put("success", true);
            response.put("message", "已记录伤害");
            response.put("currentHealth", stats != null ? stats.getCurrentHealth() : null);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("记录伤害失败", e);
            response.put("success", false);
            response.put("message", "记录伤害失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}